package org.itboys.mobile.controller.mobile.count;

import com.wordnik.swagger.annotations.Api;
import com.wordnik.swagger.annotations.ApiOperation;
import com.wordnik.swagger.annotations.ApiParam;
import org.itboys.commons.CommonConstants;
import org.itboys.commons.utils.tools.ListUtil;
import org.itboys.framework.spring.controller.BaseController;
import org.itboys.mdl.util.MobileSignUtils;
import org.itboys.mobile.common.SundayCommonConstants;
import org.itboys.mobile.dto.count.MdlCountDto;
import org.itboys.mobile.service.mongo.mobile.count.MdlMobileCountService;
import org.itboys.mobile.util.AccountIdHoldUtils;
import org.itboys.mobile.util.ResponseMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 作者：zzq
 * 时间：2017/12/5
 * 描述：迈迪龙_手机_结算
 */
@Controller
@RequestMapping("/mdl/mobile/count")
@Api(value = "count",description = "结算")
public class MdlMobileCountController extends BaseController{
    @Autowired
    private MdlMobileCountService countService;
    /**
     * 【用户版和管理版】购物车结算（确认订单）。
     * @param request
     * @param response
     * @param cartIds
     */
    @RequestMapping(value="/countCart",method= RequestMethod.POST)
    @ApiOperation(value="【用户版和管理版】购物车结算（确认订单）。")
    public void countCart(HttpServletRequest request,
                          HttpServletResponse response,

                          @ApiParam(required = true, name = "cartIds", value = "购物车ID集合(非商品ID)。如：cardIds=1,2,3。）") @RequestParam(value = "cartIds", required = true) List<Long> cartIds,
                          @ApiParam(required = false, name = "sendType", value = "配送方式") @RequestParam(value = "sendType", required = false) Integer sendType,
                          @ApiParam(value = "随机数")@RequestParam(value = "nonce", required = true) String nonce,
                          @ApiParam(value = "签名")@RequestParam(value = "sign", required = true) String sign){

        try{
            //校检签名
           Map<String, Object> param =new HashMap<String,Object>();
            param.put("sendType", sendType);
            StringBuilder cartIdsStr=new StringBuilder();
            if(ListUtil.isNotNull(cartIds)){
                for(Long cartId:cartIds){
                    cartIdsStr.append(cartId+",");
                }
            }
            param.put("cartIds",cartIdsStr.substring(0,cartIdsStr.length()-1).toString());
            param.put("nonce", nonce);
            param.put("sign", sign);
            boolean signSer = MobileSignUtils.signCheck(param, sign);
            if(!signSer){
                logger.warn("签名校验失败");
                ResponseMessage.error(-1,"签名校验失败");
                return;
            }
            Long memberId = AccountIdHoldUtils.getMemberId();
            MdlCountDto result = countService.countCart(memberId,cartIds,SundayCommonConstants.cart_type_cart,sendType);
            ResponseMessage.success(result);
        }catch (Exception e){
            String msg = CommonConstants.ERROMSG;
            Integer code=CommonConstants.FAIL_CODE;
            //自定义异常（签名错误）
            if(e.getClass().getSimpleName().equalsIgnoreCase("ErrorException")){
                msg=e.getMessage();
                //token已过期
            }else  if(e.getClass().getSimpleName().equalsIgnoreCase("TokenException")){
                code=CommonConstants.TOKEN_CODE;
                msg=CommonConstants.TOKENMSG;
            }else{
                logger.error("/mdl/mobile/count/countCart----e="+e.getMessage());
            }
            e.printStackTrace();
            ResponseMessage.error(code,msg);
        }
    }

    /**
     * 【用户版和管理版】立即购买结算（确认订单）。
     * @param request
     * @param response
     * @param productId
     * @param number
     */
    @RequestMapping(value="/countBuyNow",method= RequestMethod.POST)
    @ApiOperation(value="【用户版和管理版】立即购买结算（确认订单）")
    public void countBuyNow(HttpServletRequest request,
                            HttpServletResponse response,
                            @ApiParam(required = true, name = "productId", value = "商品ID") @RequestParam(value = "productId", required = true)Long  productId,
                            @ApiParam(required = true, name = "number", value = "购买数量") @RequestParam(value = "number", required = true) Integer number,
                            @ApiParam(required = true, name = "sendType", value = "配送方式") @RequestParam(value = "sendType", required = false) Integer sendType,
                            @ApiParam(value = "随机数")@RequestParam(value = "nonce", required = true) String nonce,
                            @ApiParam(value = "签名")@RequestParam(value = "sign", required = true) String sign) {
        try{
            //校检签名
            Map<String, Object> param =new HashMap<String,Object>();
            param.put("productId", productId);
            param.put("number", number);
            param.put("sendType", sendType);
            param.put("nonce", nonce);
            param.put("sign", sign);
            boolean signSer = MobileSignUtils.signCheck(param, sign);
            if(!signSer){
                logger.warn("签名校验失败");
                ResponseMessage.error(-1,"签名校验失败");
                return;
            }
            Long memberId = AccountIdHoldUtils.getMemberId();
            MdlCountDto result = countService.countBuyNow(memberId, productId, number,sendType);
            ResponseMessage.success(result);
        }catch (Exception e){
            String msg =CommonConstants.ERROMSG;
            Integer code=CommonConstants.FAIL_CODE;
            //自定义异常（签名错误）
            if(e.getClass().getSimpleName().equalsIgnoreCase("ErrorException")){
                msg=e.getMessage();
                //token已过期
            }else  if(e.getClass().getSimpleName().equalsIgnoreCase("TokenException")){
                code=CommonConstants.TOKEN_CODE;
                msg=CommonConstants.TOKENMSG;
            }else{
                logger.error("/mdl/mobile/count/countBuyNow----e="+e.getMessage());
            }
            e.printStackTrace();
            ResponseMessage.error(code,msg);
        }
    }
}
